import CreateForm from '@/pages/TableList/components/CreateForm';
import UpdateModal from '@/pages/TableList/components/UpdateForm';
import {
  addPostUsingPOST,
  deletePostUsingPOST,
  listPostByPageUsingPOST,
  offInterfanceUsingPOST,
  puhlishInterfanceUsingPOST,
  updatePostUsingPOST,
} from '@/services/lmxapibackend/interfanceInfoController';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import '@umijs/max';
import { Button, Drawer, message } from 'antd';
import { SortOrder } from 'antd/es/table/interface';
import React, { useRef, useState } from 'react';
// import type { FormValueType } from './components/UpdateForm.tsx.bak';
// import UpdateForm from './components/UpdateForm.tsx.bak';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.InterfanceInfoAddRequest) => {
  const hide = message.loading('正在添加');
  try {
    let res = await addPostUsingPOST({
      ...fields,
    });

    hide();
    console.log(res);
    if (res.code === 0 && res.data != null) {
      message.success('Added successfully');
    } else {
      hide();
      message.error(res.message);
    }
    return true;
  } catch (error) {
    hide();
    message.error('Adding failed, please try again!');
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.InterfanceInfoUpdateRequest) => {
  const hide = message.loading('Configuring');
  try {
    let res = await updatePostUsingPOST(fields);
    hide();
    if (res.code === 0 && res.data != null) {
      message.success('Configuration is successful');
    } else {
      hide();
      message.error('Configuration failed, please try again!');
      return false;
    }

    return true;
  } catch (error) {
    message.error('update failed, please try again!');
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.InterfanceInfo[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    for (const item of selectedRows) {
      let res = await deletePostUsingPOST({
        id: item.id,
      });
    }

    hide();
    // if (res.code==0 && res.data!=null){
    message.success('Deleted successfully and will refresh soon');
    return true;
  } catch (error) {
    message.error('delete failed, please try again!');
    return false;
  }
};

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.InterfanceInfo>();
  const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);
  /**
   * 发布接口的函数
   * */
  const handleOnline = async (record: API.InterfanceInfo) => {
    const hide = message.loading('正在发布');
    if (!record) return true;
    try {
      let res = await puhlishInterfanceUsingPOST({
        id: record.id,
      });
      hide();
      if (res.code === 0 && res.data) {
        message.success('发布成功');
        actionRef.current?.reload();
      } else {
        message.success(res.message);
      }
      return true;
    } catch (e) {
      message.error('发布失败，请重试');
      console.log(e);
      return false;
    }
  };

  /**
   * 下线接口的函数
   * */
  const handleOffline = async (record: API.InterfanceInfo) => {
    const hide = message.loading('正在发布');
    if (!record) return true;
    try {
      let res = await offInterfanceUsingPOST({
        id: record.id,
      });
      hide();
      if (res.code === 0 && res.data) {
        message.success('下线成功');
        actionRef.current?.reload();
      } else {
        message.success(res.message);
      }
      return true;
    } catch (e) {
      message.error('下线失败，请重试');
      console.log(e);
      return false;
    }
  };
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const columns: ProColumns<API.InterfanceInfo>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '接口名称',
      dataIndex: 'name',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
    },

    {
      title: '描述',
      dataIndex: 'decprition',
      valueType: 'textarea',
    },
    {
      title: '主机地址或域名',
      dataIndex: 'host',
      // sorter: true,
      // hideInForm: true,
      valueType:"text"
    },
    {
      title: 'url',
      dataIndex: 'url',
      // sorter: true,
      // hideInForm: true,
      renderText: (val: string) => `${val}`,
    },
    {
      title: '请求方式',
      dataIndex: 'method',
      // sorter: true,
      // hideInForm: true,
      renderText: (val: string) => `${val}`,
    },
    {
      title: '请求参数',
      dataIndex: 'parameters',
      valueType:"jsonCode"
      // sorter: true,
      // hideInForm: true,
      // renderText: (val: string) => `${val}`,
    },
    {
      title: '请求头',
      dataIndex: 'requestheader',
      valueType: 'textarea',
      // sorter: true,
      // hideInForm: true,
      // renderText: (val: string) => `${val}`,
    },
    {
      title: '响应头',
      dataIndex: 'reposeheader',
      valueType: 'textarea',
      // sorter: true,
      // hideInForm: true,
      // renderText: (val: string) => `${val}`,
    },
    {
      title: '创建用户',
      dataIndex: 'userid',
      // sorter: true,
      hideInForm: true,
      renderText: (val: string) => `${val}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      // hideInForm: true,
      valueEnum: {
        0: {
          text: '关闭',
          status: 'Default',
        },
        1: {
          text: '发布',
          status: 'Processing',
        },
      },
    },
    // {
    //   title: '上次调度时间',
    //   sorter: true,
    //   dataIndex: 'updatedAt',
    //   valueType: 'dateTime',
    //   renderFormItem: (item, { defaultRender, ...rest }, form) => {
    //     const status = form.getFieldValue('status');
    //     if (`${status}` === '0') {
    //       return false;
    //     }
    //     if (`${status}` === '3') {
    //       return <Input {...rest} placeholder={'请输入异常原因！'} />;
    //     }
    //     return defaultRender(item);
    //   },
    // },
    {
      title: '创建时间',
      dataIndex: 'createtime',
      valueType: 'date',
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInForm: true,
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            setCurrentRow(record);
            handleUpdateModalOpen(true);
          }}
        >
          更新
        </a>,

        <a
          key="delete"
          onClick={() => {
            setCurrentRow(record);
            handleRemove([record]);
            actionRef.current?.reload();
          }}
        >
          删除
        </a>,
        record.status === 0 ? (
          <Button
            danger
            type={"primary"}
            key="online"
            onClick={() => {
              setCurrentRow(record);
              handleOnline(record);
              actionRef.current?.reload();
            }}
          >
            发布
          </Button>
        ) : null,
        record.status === 1 ? (
          <Button
            danger

            key="offline"
            onClick={() => {
              setCurrentRow(record);
              handleOffline(record);
              actionRef.current?.reload();
            }}
          >
            下线
          </Button>
        ) : null,
        // <Button
        //   type="primary"
        //   key="primary"
        //   onClick={() => {
        //     handleUpdateModalOpen(true);
        //     setCurrentRow(record);
        //   }}
        // >
        //   更新
        // </Button>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (
          params: API.InterfanceInfoQueryRequest & {
            pageSize?: number;
            current?: number;
            keyword?: string;
          },
          sort: Record<string, SortOrder>,
          filter: Record<string, React.ReactText[] | null>,
        ) => {
          let newVar = await listPostByPageUsingPOST(params);
          // let result:RequestData<API.InterfanceInfo>={

          return {
            data: newVar.data?.records || [],
            success: true,
            total: newVar.data?.total,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)} 万
              </span>
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}

      {/*<ModalForm*/}
      {/*  title={'新建规则'}*/}
      {/*  width="400px"*/}
      {/*  open={createModalOpen}*/}
      {/*  onOpenChange={handleModalOpen}*/}
      {/*  onFinish={async (value) => {*/}
      {/*    const success = await handleAdd(value as API.RuleListItem);*/}
      {/*    if (success) {*/}
      {/*      handleModalOpen(false);*/}
      {/*      if (actionRef.current) {*/}
      {/*        actionRef.current.reload();*/}
      {/*      }*/}
      {/*    }*/}
      {/*  }}*/}
      {/*>*/}
      {/*  <ProFormText*/}
      {/*    rules={[*/}
      {/*      {*/}
      {/*        required: true,*/}
      {/*        message: '规则名称为必填项',*/}
      {/*      },*/}
      {/*    ]}*/}
      {/*    width="md"*/}
      {/*    name="name"*/}
      {/*  />*/}
      {/*  <ProFormTextArea width="md" name="desc" />*/}
      {/*</ModalForm>*/}

      <UpdateModal
        columns={columns}
        onSubmit={async (value) => {
          console.log(currentRow);
          console.log(value);
          value.id = currentRow?.id;
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          console.log(currentRow);
          handleUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        visible={updateModalOpen}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>

      <CreateForm
        columns={columns}
        onCancel={() => {
          handleModalOpen(false);
          console.log('执行cancel方法');
        }}
        onSubmit={async (value) => {
          console.log(value);
          await handleAdd(value as API.InterfanceInfoAddRequest);
          handleModalOpen(false);
        }}
        visible={createModalOpen}
      />
    </PageContainer>
  );
};
export default TableList;
